package com.example.my_model.loginactivity;

import androidx.room.Room;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.example.common.BaseApplication;
import com.example.common.filed.DataActionEntity;
import com.example.common.filed.EventBusAction;
import com.example.common.mvvm.viewmodel.BaseViewModel;
import com.example.my_model.accountentity.AccountEntity;
import com.example.my_model.accountentity.DataDTO;
import com.example.my_model.entity.UserInsertEntity;
import com.example.my_model.room.UserDao;
import com.example.my_model.room.UserDataBase;
import com.example.my_model.room.UserEntity;
import com.example.network_skd.BaseEntity;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginViewModel extends BaseViewModel<LoginRepository> {

    private UserDataBase db;

    @Override
    protected void initData() {
        db = Room.databaseBuilder(BaseApplication.getInstance(), UserDataBase.class, "user.db").build();
    }

    @Override
    protected void onResult(BaseEntity baseEntity) {
        if (baseEntity instanceof UserInsertEntity){
            UserInsertEntity userInsertEntity = (UserInsertEntity) baseEntity;
            DataActionEntity dataActionEntity = new DataActionEntity();
            dataActionEntity.action = "FINISHPAGE";
            vmData.post(dataActionEntity);
            EventBusAction eventBusAction = new EventBusAction();
            eventBusAction.action="refreshUserInfo";
            EventBus.getDefault().post(eventBusAction);

            return;
        }
        if (baseEntity instanceof AccountEntity){
            AccountEntity accountEntity = (AccountEntity) baseEntity;
            DataDTO data = accountEntity.data.data;
            SPUtils.getInstance().put("userId", data.userId);
            //登录成功保存数据库
            repository.insertUser(db.userDao(), data)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this);

        }
    }


    public void requestAddUser(UserEntity userEntity){
        repository.requestAddAccount(userEntity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

}
